<template>

  <el-row :gutter="10" type="flex" align="middle" style="margin: 20px 0;">

    <el-col :span="10">
      <el-select v-model="selectedType">
        <el-option
            v-for="type in queryType"
            :label="type.label"
            :value="type.value"
        >
        </el-option>
      </el-select>
    </el-col>

    <el-col :span="4">
      <el-button @click="queryByType" type="success" plain>分类搜索</el-button>
    </el-col>
  </el-row>

  <!--  查询 -->
  <div style="margin: 20px 0;">
    <el-input placeholder="请输入客户姓名" style="width:200px" v-model="queryName"></el-input>
    <el-button @click="queryByName" type="success" plain>查询</el-button>


    <el-button @click="isQuery? showRecordTable(0,null) : back()" type="primary" style="width: 100px; margin-left: 50px;font-weight: bolder; font-size: 16px">
      {{ isQuery ? '登 记' : '返 回' }}&emsp;
    </el-button>
  </div>
  <!--  显示所有外出申请信息 table自动循环-->
  <div>{{errorMessage}}</div>
  <el-table :data="OutwardList">
    <el-table-column label="序号" type="index" width="60px"></el-table-column>
    <el-table-column prop="customer.customerName" label="客户姓名" width="80px"></el-table-column>
    <el-table-column prop="customer.contactTel" label="客户电话" width="80px"></el-table-column>
    <el-table-column prop="outgoingreason" label="外出事由" width="80px"></el-table-column>
    <el-table-column prop="outgoingtime" label="外出时间" width="80px" :formatter="formatDate"></el-table-column>
    <el-table-column prop="expectedreturntime" label="预计回院时间" width="80px" :formatter="formatDate"></el-table-column>
    <el-table-column prop="actualreturntime" label="实际回院时间" width="80px" :formatter="formatDate"></el-table-column>
    <el-table-column prop="escorted" label="陪同人" width="80px"></el-table-column>
    <el-table-column prop="relation" label="陪同人关系" width="80px"></el-table-column>
    <el-table-column prop="escortedtel" label="陪同人电话" width="80px"></el-table-column>


    <el-table-column prop="remarks" label="备注" width="120px"></el-table-column>
    <el-table-column  label="操作" v-if="isQuery">
      <template #default="scope">

        <el-button
            v-if="scope.row.customer.isIner === 1"
            @click="showRecordTable(1,scope.row)"
            type="primary"
            plain
        >
          外出
        </el-button>


        <el-button
            v-else
            @click="showReturnDialog(scope.row)"
            type="success"
            plain
        >
          返院
        </el-button>




      </template>
    </el-table-column>
  </el-table>

  <div class="example-pagination-block">
    <el-pagination background
                   v-model:current-page="pageContains.pageNum"
                   v-model:page-size="pageContains.pageSize"
                   :page-sizes="[10,20,30,50,100]"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="pageContains.total"
                   @size-change="handleSizeChange"
                   @current-change="handlePageChange"
    />
  </div>



  <!--  外出登记信息对话框 -->
  <el-dialog v-model="outwardDialog" title="外出登记信息">
    <el-form :model="newRecord">



      <el-form-item label="客户姓名">
        <el-col :span="11">
          <el-select v-model="newRecord.customer.customerName" :disabled="isEdit">
            <el-option
                v-for="cutomer in customerOptions"

                :key="cutomer.id"
                :label="cutomer.customerName"
                :value="cutomer.customerName"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>

      <el-form-item label="外出事由">
        <el-col :span="11">
          <el-input v-model="newRecord.outgoingreason"></el-input>
        </el-col>
      </el-form-item>

      <el-form-item label="外出时间" >
        <el-col :span="11">
          <el-date-picker v-model="newRecord.outgoingtime" type="datetime"></el-date-picker>
        </el-col>
      </el-form-item>

      <el-form-item label="预计回院时间" >
        <el-col :span="11">
          <el-date-picker v-model="newRecord.expectedreturntime" type="datetime"></el-date-picker>
        </el-col>
      </el-form-item>

      <el-form-item label="陪同人">
        <el-col :span="11">
          <el-input v-model="newRecord.escorted"></el-input>
        </el-col>
      </el-form-item>

      <el-form-item label="陪同人关系">
        <el-col :span="11">
          <el-input v-model="newRecord.relation"></el-input>
        </el-col>
      </el-form-item>

      <el-form-item label="陪同人电话">
        <el-col :span="11">
          <el-input v-model="newRecord.escortedtel"></el-input>
        </el-col>
      </el-form-item>


      <el-form-item label="备注">
        <el-col :span="11">
          <el-input v-model="newRecord.remarks"></el-input>
        </el-col>
      </el-form-item>


    </el-form>
    <el-button @click="addOutRecord()">{{"登记"}}</el-button>
  </el-dialog>



<!--  返回会话表-->
  <el-dialog v-model="returnDialog" title="实际返回时间表">


    <el-form :model="newRecord">
      <el-form-item label="实际返院时间" >
        <el-col :span="11">
          <el-date-picker v-model="newRecord.actualreturntime" type="datetime"></el-date-picker>
        </el-col>
      </el-form-item>
    </el-form>


    <el-button @click="isback()">{{"确认"}}</el-button>
  </el-dialog>


</template>







<script setup>
import {ref, onMounted, reactive} from "vue";
import http from '@/axios/http';
import qs from "qs";
// 存放外出数据集合
let OutwardList = ref([]);

//报错提示
let errorMessage = ref("")

//模糊查询绑定的 客户名称
let queryName = ref("")

//控制操作按钮的显示
let isQuery = ref("")

let isEdit = ref(false);

//对话框显示控制
let outwardDialog = ref(false)
let returnDialog = ref(false)

let newRecord = ref({
  customer: {
    customerName: ""
  },
});

let customerOptions = ref({})

const selectedType = ref(2); // 默认选中"全部"

let queryType = ref([
  {
    label: "全部",
    value: 2
  },{
    label: '在院',
    value: 1
  },{
    label: '外出',
    value: 0
  }
])

let size = 10; //当前显示多少行
let pageNum = 1; // 当前页码
let pageSize = 10; //每页显示行数

//当前页码信息
let pageContains = ref({})


function showRecordTable(type,row){
  newRecord.value = {
    customer: {
      customerName: type === 0 ? "" : row?.customer?.customerName || ""
    },
    outgoingreason: "",
    outgoingtime: "",
    expectedreturntime: "",
    escorted: "",
    relation: "",
    escortedtel: "",
    remarks: ""
  };

  if (type == 0){
    isEdit.value = false;
  }
  else {
    isEdit.value = true;
  }


  //获取姓名下拉框
  http.post('/lyy/get_iner_customernames').then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 customerOptions
        if(result.result === 'success'){
          customerOptions.value = result.data;
        } else {
          errorMessage.value = result.error;
        }

      }
  )

  outwardDialog.value = true;

}

//根据客户姓名模糊查询外出信息
function queryByName(){

  isQuery.value = false;

  let param = {
    customer: {
      customerName: queryName.value
    }
  }

  http.post('/lyy/get_outrecord_by', param).then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 OutwardList
        if(result.result === 'success'){
          OutwardList.value = result.data;
        } else {
          errorMessage.value = result.error;
        }

      }
  )

  queryName.value = "";
}

function addOutRecord(){

  let param = newRecord.value;


  http.post('/lyy/add_out_record', param).then(
      (res)=>{
        let result = res.data;
        if(result.result === 'success'){
          //关闭对话框
          outwardDialog.value = false;

          //刷新在外列表
          queryByName();
        } else {
          errorMessage.value = result.error;
        }

      }
  )

}



function back(){
  getAllCustomer();
}

function queryByType(){

  if (selectedType.value == 2){
    getAllCustomer();
  }
  else {
    getIsinerCustomer(selectedType.value)
  }
}




//页面初始化
onMounted(
    ()=>{
      init();
    }
)

function init(){
  //查询所有外出记录信息
  getAllCustomer();
  //查询需要的字典（{标志1: 值1, 标志2: 值2}）
  //用的时候取 字典[字段值（字典标志）]
}


function getAllCustomer(){
  isQuery.value = true;

  let params = ref({
    size: size,
    pageNum: pageNum,
    pageSize: pageSize,
  })

  http.post('/lyy/get_all_OutStatus', params.value).then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 OutwardList
        if(result.result === 'success'){
          pageContains.value = result.data;
          //pageContains.list = null;
          OutwardList.value = result.data.list;

        } else {
          errorMessage.value = result.error;
        }

      }
  )
}

function getIsinerCustomer(){
  isQuery.value = true;

  let params = ref({
    size: size,
    pageNum: pageNum,
    pageSize: pageSize,
    type: selectedType
  })

  http.post('/lyy/get_Isiner_customer', params.value).then(
      (res)=>{
        let result = res.data;
        // 返回结果传给 OutwardList
        if(result.result === 'success'){
          pageContains.value = result.data;
          //pageContains.list = null;
          OutwardList.value = result.data.list;

        } else {
          errorMessage.value = result.error;
        }
      }
  )
}

//显示编辑对话框
function showReturnDialog(row){

  //显示对话框
  returnDialog.value = true;
  newRecord.value = {
    id: row.id,
    actualreturntime: row.actualreturntime,
    customer: {
      id: row.customer.id,
      isIner: row.customer.isIner
    }
  };

}

function showOutDialog(row){
  returnDialog.value = true;
  newRecord.value = {
    id: row.id,
    actualreturntime: row.actualreturntime,
    customer: {
      id: row.customer.id,
      isIner: row.customer.isIner
    }
  };
}


function isback(){
  // 只传递必要的参数
  let param = {
    id: newRecord.value.id,
    actualreturntime: newRecord.value.actualreturntime,
    customerId: newRecord.value.customer.id,  // 直接使用customerId而不是嵌套对象
    isIner: newRecord.value.customer.isIner  // 直接传递isIner
  };

  http.post('/lyy/set_return_time', param).then(
      (res)=>{
        let result = res.data;
        if(result.result === 'success'){
          returnDialog.value = false;
          queryByName();
        } else {
          errorMessage.value = result.error;
        }
      }
  )
}

//格式化日期
function formatDate(row, column){
  let data = row[column.property];

  if(data == null){
    return null;
  }

  let dt = new Date(data);
  return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
  + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
}

//分页处理
const handlePageChange = (pageNum1)=>{
  pageNum = pageNum1
  if (selectedType.value == 2){
    getAllCustomer()
  }
  else {
    getIsinerCustomer(selectedType.value)
  }
}

const handleSizeChange = (pageSize1)=>{
  pageSize = pageSize1
  if (selectedType.value == 2){
    getAllCustomer()
  }
  else {
    getIsinerCustomer(selectedType.value)
  }
}
</script>

<style scoped>

</style>